package cn.xyf.eduservice.listener;

import cn.xyf.eduservice.domain.EduSubject;
import cn.xyf.eduservice.domain.excel.SubjectData;
import cn.xyf.eduservice.service.EduSubjectService;
import cn.xyf.servicebase.handler.MyException;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    /**
     * 因为 SubjectExcelListener 不能交给spring进行管理，需要自己 new，不能注入其他对象
     * 所以不能实现数据库操作
     * 所以就直接把 eduSubjectService 传递过来
     */

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    // 一行一行读取Excel数据
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new MyException(201, "文件数据为空");
        }

        // 判断一级分类是否重复
        EduSubject existOneSubject = this.existOneSubject(eduSubjectService, subjectData.getOneSubjectName());
        if (existOneSubject == null) {
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0"); // 父类id默认0
            existOneSubject.setTitle(subjectData.getOneSubjectName()); // 一级分类名称
            eduSubjectService.save(existOneSubject);
        }

        String pid = existOneSubject.getId();
        // 判断二级分类是否重复
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService, subjectData.getTwoSubjectName(), pid);
        if (existTwoSubject == null) {
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid); // 设置id
            existTwoSubject.setTitle(subjectData.getTwoSubjectName()); // 二级分类名称
            eduSubjectService.save(existTwoSubject);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    // 判断一级分类不能重复添加
    public EduSubject existOneSubject(EduSubjectService subjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        // System.out.println("one*******" + oneSubject);
        return oneSubject;
    }

    // 判断二级分类不能重复添加
    public EduSubject existTwoSubject(EduSubjectService subjectService, String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        // System.out.println("two*******" + twoSubject);
        return twoSubject;
    }
}
